﻿@page "/pages/contacts/edit/{id:int}"
@using CleanArchitecture.Blazor.Application.Features.Contacts.Commands.Update
@using CleanArchitecture.Blazor.Application.Features.Contacts.Queries.GetById
@using CleanArchitecture.Blazor.Server.UI.Components.Fusion

@inherits MudComponentBase
@inject IValidationService Validator
@inject IStringLocalizer<Contacts> L
@attribute [Authorize(Policy = Permissions.Contacts.Edit)]

<PageTitle>@Title</PageTitle>
<Breadcrumbs OnSaveButtonClick="OnSubmit" Saving="_saving" BreadcrumbItems="_breadcrumbItems"></Breadcrumbs>
<MudContainer Class="mt-3" MaxWidth="MaxWidth.Large">
@if (_model != null)
{
    <MudCard Class="pa-2">
        <MudCardHeader>
            <CardHeaderContent>
                 <MudText Typo="Typo.h6">@Title</MudText>
            </CardHeaderContent>
        </MudCardHeader>
        <MudCardContent>
        <ActiveUserSession PageComponent="@($"{nameof(EditContact)}/{ _model.Id }")" />
        <MudForm Model="@_model" @ref="@_contactForm" Validation="@(Validator.ValidateValue(_model))">
            <MudGrid Spacing="2">
                <MudItem xs="12" md="6"> 
                        <MudTextField Label="@L[_model.GetMemberDescription(x=>x.Name)]" @bind-Value="_model.Name" For="@(() => _model.Name)" Required="true" RequiredError="@L["name is required!"]"></MudTextField>
                </MudItem> 
<MudItem xs="12" md="6"> 
                        <MudTextField Label="@L[_model.GetMemberDescription(x=>x.Description)]"  For="@(() => _model.Description)" @bind-Value="_model.Description"></MudTextField>
                </MudItem> 
<MudItem xs="12" md="6"> 
                        <MudTextField Label="@L[_model.GetMemberDescription(x=>x.Email)]" @bind-Value="_model.Email" For="@(() => _model.Email)" Required="false" RequiredError="@L["email is required!"]"></MudTextField>
                </MudItem> 
<MudItem xs="12" md="6"> 
                        <MudTextField Label="@L[_model.GetMemberDescription(x=>x.PhoneNumber)]" @bind-Value="_model.PhoneNumber" For="@(() => _model.PhoneNumber)" Required="false" RequiredError="@L["phone number is required!"]"></MudTextField>
                </MudItem> 
<MudItem xs="12" md="6"> 
                        <MudTextField Label="@L[_model.GetMemberDescription(x=>x.Country)]" @bind-Value="_model.Country" For="@(() => _model.Country)" Required="false" RequiredError="@L["country is required!"]"></MudTextField>
                </MudItem> 

            </MudGrid>
        </MudForm>
        </MudCardContent>
        <MudCardActions Class="d-flex justify-end gap-2">
                    <MudLoadingButton Color="Color.Primary" DropShadow="false" Loading="@_saving" OnClick="OnSubmit">@ConstantString.Save</MudLoadingButton>
        </MudCardActions>
        </MudCard>
    }
</MudContainer>
 

@code {
    public string? Title { get; private set; }
    [Parameter]
    public int Id { get; set; }
    MudForm _contactForm = new();
    private bool _saving = false;
    private List<BreadcrumbItem>? _breadcrumbItems;
    private UpdateContactCommand? _model;
    protected override async Task OnInitializedAsync()
    {
        Title = L["Edit Contact"];
        _breadcrumbItems = new List<BreadcrumbItem>
        {
            new BreadcrumbItem(L["Home"], href: "/"),
            new BreadcrumbItem(L["Contacts"], href: "/pages/contacts")
        };
        var result = await Mediator.Send(new GetContactByIdQuery() { Id = Id });
        result.Map(data =>
        {
            _model = Mapper.Map<UpdateContactCommand>(data);
            return data;
        }).Match(data =>
        {
            _breadcrumbItems.Add(new BreadcrumbItem(data.Name, href: $"/pages/contacts/edit/{Id}"));
        }, errors =>
        {
            Snackbar.Add($"{errors}", Severity.Error);
        });

    }
    async Task OnSubmit()
    {
        try
        {
            _saving = true;
            await _contactForm.Validate().ConfigureAwait(false);
            if (!_contactForm.IsValid)
                return;
            if (_model != null)
            {
                var result = await Mediator.Send(_model);
                result.Match(
                    data=>
                    {
                        Snackbar.Add(ConstantString.SaveSuccess, MudBlazor.Severity.Info);
                    },
                    errors=>
                    {
                        Snackbar.Add(errors, MudBlazor.Severity.Error);
                    });
            }
        }
        finally
        {
            _saving = false;
        }
    }
}
